package com.mpsc.singleton.demo.common;


import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice(basePackages = "需要检测异常的包名，一般为controller包")
public class ExceptionController {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResponse handleVaildException(MethodArgumentNotValidException e){
        Map<String,String> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach((item)->{
            String message = item.getDefaultMessage();
            String field = item.getField();
            map.put(field,message);
        });
        return new BaseResponse (500, "",map);
    }

}
